go-restful https basic authentication 基础认证 示例

本文介绍了一个使用 Go 语言实现的 RESTful API 服务示例,该服务通过 HTTPS 协议运行并采用基本认证确保安全性。文章展示了如何配置 RESTful 服务的基本结构、如何设置 HTTPS 证书以及如何实现基本的身份验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package main

import (
	"github.com/emicklei/go-restful"
	"log"
	"net/http"
	"os"
)

func main() {
	wsContainer := restful.NewContainer()
	wsContainer.Router(restful.CurlyRouter{})

	ws := new(restful.WebService)
	ws.
		Path("/api").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON) // 可单独设置每一个方法

	//	最终地址 https://127.0.0.1:7443/api/config
	ws.Route(ws.POST("/config").Filter(basicAuthenticate).To(config))

	ws.Filter(basicAuthenticate)//basic auth filter

	wsContainer.Add(ws)
	log.Printf("start listening on localhost:7443")
	server := &http.Server{Addr: ":7443", Handler: wsContainer}

	//证书生成方式参考https://blog.youkuaiyun.com/u011411069/article/details/79994716
	crtPath := "/home/leen/Desktop/certificate.crt"//crt 证书
	_, err := os.Stat(crtPath)
	if err != nil {
		log.Println("crt file not exist!")
		return
	}

	keyPath := "/home/leen/Desktop/certificate.key"//key 证书
	_, err = os.Stat(crtPath)
	if err != nil {
		log.Println("key file not exist!")
		return
	}

	err = server.ListenAndServeTLS(crtPath, keyPath)
	if err != nil {
		log.Println(err.Error())
	}
}

//basic auth 验证过滤
func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	// usr/pwd = admin/admin
	u, p, ok := req.Request.BasicAuth()
	if !ok || u != "admin" || p != "admin" {
		resp.AddHeader("WWW-Authenticate", "Basic realm=Protected Area")
		resp.WriteErrorString(401, "401: Not Authorized")
		return
	}
	chain.ProcessFilter(req, resp)
}

//rest请求处理方法
func config(request *restful.Request, response *restful.Response) {
	entity := new(model.TestEntity)
	err := request.ReadEntity(entity)

	if err != nil {
		response.WriteEntity(model.NewResult(500, err.Error()))
	} else {
		response.WriteEntity(model.NewResult(0, "config successful!"))
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值