当前位置: 首页 > 工具软件 > go-restful > 使用案例 >

给予go-restful插件的Web服务器---------基础篇(https)

仉刚洁
2023-12-01

目录

main.go

router.go

handlers.go


go-restful的库:github.com/emicklei/go-restful

直接贴代码的,相信都看得懂。

main.go

package main

import (
	"crypto/rand"
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/emicklei/go-restful"
)

//Route 定义路由信息
type Route struct {
	Method string
	URI    string
}

//Routes  路由接口定义
type Routes struct {
	route map[string]Route
}

//CurrentTime 当前时间,2018-12-22 14:41:21.4728403
func CurrentTime() string {
	t := time.Now()
	//fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 这是个奇葩,必须是这个时间点, 据说是go诞生之日, 记忆方法:6-1-2-3-4-5
	cur := fmt.Sprintf("%s.%9d", time.Now().Format("2006-01-02 15:04:05"), t.Nanosecond())
	return cur
}

func inittls(cfg *tls.Config, certFile, keyFile string) {
	crt, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalln(err.Error())
	}
	cfg.Time = time.Now
	cfg.Rand = rand.Reader
	cfg.Certificates = []tls.Certificate{crt}
}

func main() {
	var certFile = "./cert/cert.pem"
	var keyFile = "./cert/key.unencrypted.pem"

	wsContainer := restful.NewContainer()
	wsContainer.Router(restful.CurlyRouter{})
	inter := Routes{map[string]Route{}}
	inter.RESTFulAuthRegister(wsContainer)

	sslconfig := &tls.Config{}
	inittls(sslconfig, certFile, keyFile string)

	srv := &http.Server{
		Addr:         ":8443",
		Handler:      wsContainer,
		TLSConfig:    sslconfig,
		TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
	}

	srv.ListenAndServeTLS(certFile, keyFile)
}

跟mux框架的一样,也是需要初始化TLS,设置参数。

go-restful有容器NewContainer的概念,具体了解可以去看源码。

	inter.RESTFulAuthRegister(wsContainer)

这三个是注册路由的函数,需要自己去实现。

//RESTFulAuthRegister  ...
func (inter *Routes) RESTFulAuthRegister(container *restful.Container) {
	ws := new(restful.WebService)
	ws.
		Path("/helloworld").
		Consumes(restful.MIME_XML, restful.MIME_JSON).
		Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well

	ws.Route(ws.POST("/").To(inter.RESTFulServerTokenLoginPorc))
	ws.Route(ws.DELETE("/{username}").To(inter.RESTFulServerTokenLogoutProc))

	container.Add(ws)
}

router.go

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	restful "github.com/emicklei/go-restful"
)

//RESTFulAuthRegister  ...
func (inter *Routes) RESTFulAuthRegister(container *restful.Container) {
	ws := new(restful.WebService)
	ws.
		Path("/helloworld").
		Consumes(restful.MIME_XML, restful.MIME_JSON).
		Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well

	ws.Route(ws.POST("/").To(inter.RESTFulServerTokenLoginPorc))
	ws.Route(ws.DELETE("/{username}").To(inter.RESTFulServerTokenLogoutProc))

	container.Add(ws)
}

//RESTFulServerTokenLoginPorc POST /v3/auth/tokens
func (inter *Routes) RESTFulServerTokenLoginPorc(request *restful.Request, response *restful.Response) {
	fmt.Println()
	fmt.Println(time.Now())
	fmt.Println(CurrentTime(), "URL:\t", request.Request.URL)
	fmt.Println(CurrentTime(), "METHOD:\t", "POST")

	var token string
	response.AddHeader("content-type", restful.MIME_JSON)
	response.AddHeader("charset", "UTF-8")
	response.AddHeader("transaction-id", request.HeaderParameter("transaction-id"))

	for index := 0; index < 80; index++ {
		v := rand.Intn(10)
		token = token + strconv.Itoa(v)
	}
	//fmt.Println(token)
	response.AddHeader("X-Subject-Token", token)

	response.Write([]byte("{\"result\":\"success\"}"))
}

//RESTFulServerTokenLogoutProc DELETE /v3/auth/tokens/{username}
func (inter *Routes) RESTFulServerTokenLogoutProc(request *restful.Request, response *restful.Response) {
	fmt.Println()
	fmt.Println(time.Now())
	fmt.Println(CurrentTime(), "URL:\t", request.Request.URL)
	fmt.Println(CurrentTime(), "METHOD:\t", "DELETE")

	vars := request.PathParameters()
	username := vars["username"]

	response.AddHeader("content-type", restful.MIME_JSON)
	response.AddHeader("charset", "UTF-8")
	response.AddHeader("transaction-id", request.HeaderParameter("transaction-id"))
	//response.AddHeader("X-Auth-Token", request.HeaderParameter("X-Auth-Token"))

	strBody := fmt.Sprintf("{\"username\":\"%s\"}", username)
	response.Write([]byte(strBody))

}

注册路由信息以及实现函数,Path("/helloworld").表示跟,下面注册了POST方法以及DELETE方法,DELETE方法有个参数username.

 

handlers.go

再定义一个处理函数,被response.Write()函数调用,返回[]byte。

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	restful "github.com/emicklei/go-restful"
)

//JSONReadFileData 读取文件内容,返回byte
func JSONReadFileData(filename string) []byte {
	//ReadFile函数会读取文件的全部内容,并将结果以[]byte类型返回
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println(CurrentTime(), "JSONReadFileData: read file[", filename, "]failed.")
		return resultFAIL(20180001, "JSONReadFileData: ReadFile failed.")
	}

	//fmt.Println(CurrentTime(),data)
	fmt.Println(CurrentTime(), "JSONReadFileData: success")
	return data
}

也可以用response.WriteAsJson("{\"function\":\"vnfstatusnotify\"}"),这里的入参是string,可以自己写个处理函数,返回string,在这里去调用。

 类似资料: