B
B
Bekkazy2019-01-26 14:21:27
go
Bekkazy, 2019-01-26 14:21:27

How to implement an interface where you can register functions like http.HandleFunc?

It is necessary to do almost the same as in the net/http package. First
, register type handlers :
mypackage.RegisterHandler("/path", handler)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
igorzakhar, 2019-01-26
@Bekkazy

Something like this (if I understood your question correctly):

package main

import (
  "fmt"
)

type HandlersMap map[string]func(string) string

func (hm HandlersMap) RegisterHandler(path string, handler func(string) string) {
  hm[path] = handler
}

func main() {
  m := make(HandlersMap, 0)

  m.RegisterHandler("1", myFunc1)
  m.RegisterHandler("2", myFunc2)

  handler1 := m["1"]
  handler2 := m["2"]

  fmt.Println(handler1("handler 1 output"))
  fmt.Println(handler2("handler 2 output"))
}

func myFunc1(s string) string {
  return fmt.Sprintf("MyFunc1: %s", s)
}

func myFunc2(s string) string {
  return fmt.Sprintf("MyFunc2: %s", s)
}

$ go run main.go 
MyFunc1: handler 1 output
MyFunc2: handler 2 output

S
stratosmi, 2019-01-26
@stratosmi

All three of these libraries can register a Handler from net/http:

  1. https://github.com/go-ozzo/ozzo-routing
  2. www.gorillatoolkit.org/pkg/pat
  3. www.gorillatoolkit.org/pkg/mux

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question