go 起server

go 起server,第1张

package services

import (

    "context"

    "net/http"

    "os"

    "github.com/node-scheduler/node-scheduler/pkg/log"

)

type httphandle func(w http.ResponseWriter, r *http.Request)

type Server struct {

    Baseurl   string

    ctx       context.Context

    logger    log.T

    Actionmap map[string]httphandle

}

func action0(w http.ResponseWriter, r *http.Request) {

    w.Write([]byte("action0"))

}

func action1(w http.ResponseWriter, r *http.Request) {

    w.Write([]byte("action1"))

}

func action2(w http.ResponseWriter, r *http.Request) {

    w.Write([]byte("action2"))

}

func NewServer(ctx context.Context, logger log.T) *Server {

    return &Server{

        Baseurl: "127.0.0.1:8080",

        Actionmap: map[string]httphandle{

            "/url0": action0,

            "/url1": action1,

            "/url2": action2,

        },

        logger: logger,

        ctx:    ctx,

    }

}

func (sr *Server) Start() {

    for url, action := range sr.Actionmap {

        http.HandleFunc(url, action)

    }

    err := http.ListenAndServe("127.0.0.1:8080", nil)

    if err != nil {

        sr.logger.Errorf("start http server fail %s", err.Error())

        os.Exit(-1)

    }

}

RESTfull格式

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995084.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存