首页 > 其他分享 >go web框架

go web框架

时间:2024-05-24 18:07:39浏览次数:26  
标签:web http 框架 err fmt gitlab func Error go

  • net/http
  • gin-gonic/gin
  • go-chi/chi
  • gorilla/mux

 

其中gin 我是用的最多,但是在最近的使用中我有一些特殊需求,比如 /gitlab/{uuid}/notify,我只获取{uuid}的值才能满足,gin 不能更好的满足我的需求

这时候 gorilla/mux 就能满足我的需求

 

 

 

 

package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/go-playground/webhooks/v6/gitlab"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

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

	ctx := r.Context()

	fmt.Println("ctx:", ctx)

	XGitlabToken, ok := ctx.Value("X-Gitlab-Token").(string)
	if !ok {
		http.Error(w, http.StatusText(422), 422)
		return
	}
	fmt.Println("X-Gitlab-Token", XGitlabToken)

	fmt.Println("r.Header.Get(\"X-Gitlab-Token\")", r.Header.Get("X-Gitlab-Token"))
	vars := mux.Vars(r)
	name := vars["uuid"]
	w.Write([]byte("Hello, " + name + "!"))
	//hook, err := gitlab.New(gitlab.Options.Secret("122333"))
	hook, err := gitlab.New()
	if err != nil {

		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	payload, err := hook.Parse(r, gitlab.PushEvents, gitlab.TagEvents, gitlab.MergeRequestEvents, gitlab.BuildEvents, gitlab.JobEvents, gitlab.PipelineEvents)
	if err != nil {
		if errors.Is(err, gitlab.ErrEventNotFound) {
			// ok event wasn't one of the ones asked to be parsed
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if errors.Is(err, gitlab.ErrGitLabTokenVerificationFailed) {
			// ok event wasn't one of the ones asked to be parsed
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		fmt.Println("err", err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if payload == nil {
		fmt.Println(payload)
	}

	switch payload.(type) {

	case gitlab.MergeRequestEventPayload:
		release := payload.(gitlab.MergeRequestEventPayload)
		// Do whatever you want from here...
		fmt.Printf("%+v", release)

	case gitlab.PushEventPayload:
		pushRequest := payload.(gitlab.PushEventPayload)
		// Do whatever you want from here...
		fmt.Printf("%+v", pushRequest)

	case gitlab.TagEventPayload:
		TagRequest := payload.(gitlab.TagEventPayload)
		// Do whatever you want from here...
		fmt.Printf("%+v", TagRequest)
	}
	_, err = io.WriteString(w, r.URL.Path)
	if err != nil {
		return
	}

}

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

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := h(w, r); err != nil {
		// handle returned error here.
		w.WriteHeader(503)
		w.Write([]byte("bad"))
	}
}

// MyMiddleware HTTP middleware setting a value on the request context
func MyMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// create new context from `r` request context, and assign key `"user"`
		// to value of `"123"`
		ctx := context.WithValue(r.Context(), "X-Gitlab-Token", r.Header.Get("X-Gitlab-Token"))

		// call the next handler in the chain, passing the response writer and
		// the updated request object with the new context value.
		//
		// note: context.Context values are nested, so any previously set
		// values will be accessible as well, and the new `"user"` key
		// will be accessible from this point forward.
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func main() {
	// 创建一个新的路由器
	r := mux.NewRouter()

	//// 定义一个路由
	//r.HandleFunc("/gitlab/{uuid}/notify", func(w http.ResponseWriter, r *http.Request) {
	//	vars := mux.Vars(r)
	//	name := vars["uuid"]
	//	w.Write([]byte("Hello, " + name + "!"))
	//}).Methods("POST")


	r.Use(MyMiddleware)

	r.HandleFunc("/gitlab/{uuid}/notify", gitlabWebhook).Methods("POST")


	loggedRouter := handlers.LoggingHandler(os.Stdout, r)



	srv := &http.Server{
		Addr: ":8080",
		// Good practice to set timeouts to avoid Slowloris attacks.
		WriteTimeout: time.Second * 15,
		ReadTimeout:  time.Second * 15,
		IdleTimeout:  time.Second * 60,
		Handler:      loggedRouter, // Pass our instance of gorilla/mux in.
	}



	go func() {

		// 服务连接
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			//errChan <- err
			log.Fatalf("listen: %s\n", err)

		}

	}()



	c := make(chan os.Signal, 1)
	// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
	// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
	signal.Notify(c, os.Interrupt)

	// Block until we receive our signal.
	<-c


	wait := time.Second * 60
	// Create a deadline to wait for.
	ctx, cancel := context.WithTimeout(context.Background(), wait)
	defer cancel()
	// Doesn't block if no connections, but will otherwise wait
	// until the timeout deadline.
	srv.Shutdown(ctx)
	// Optionally, you could run srv.Shutdown in a goroutine and block on
	// <-ctx.Done() if your application should wait for other services
	// to finalize based on context cancellation.
	log.Println("shutting down")
	os.Exit(0)

}

  

标签:web,http,框架,err,fmt,gitlab,func,Error,go
From: https://www.cnblogs.com/leon-coder/p/18211481

相关文章

  • .Net6 web API (ResouceFilter-ActionFilter)
    前沿net中的ResouceFilter和ActionFilter 有啥主要区别呢其实2者都是过滤器 在ASP.NETCore中,ResourceFilter和ActionFilter是两种不同类型的过滤器,用于在请求处理过程中执行额外的逻辑。它们可以用于对请求和响应进行处理、修改或拦截,以实现诸如授权、日志记录......
  • 三、Web自动化测试(3)
    一、PO模式v1:不使用任何设计模式和单元测试框架v2:使用pytest管理用例v3:使用方法封装的思想,对代码进行优化v4:采用PO模式的分层思想对代码进行拆分,分离pagev5:对PO分层后的代码继续优化,分离page中的元素和操作v6:PO模式深入封装,把共同操作提......
  • CS2 CSGO2反恐精英2服务器开服联机教程
    1、购买后登录服务器(百度莱卡云)进入控制面板后会出现正在安装的界面,游戏将近40G需要,安装时间相比较长(如超过30分钟处于安装中请联系我们的客服人员)2、更改端口2.1、点击网络就可以看到有两个已经创建好的端口首选端口必须是游戏端口,则另一个就是RCON端口2.2、复制RC......
  • LLM 大模型学习必知必会系列(十一):大模型自动评估理论和实战以及大模型评估框架详解
    LLM大模型学习必知必会系列(十一):大模型自动评估理论和实战以及大模型评估框架详解0.前言大语言模型(LLM)评测是LLM开发和应用中的关键环节。目前评测方法可以分为人工评测和自动评测,其中,自动评测技术相比人工评测来讲,具有效率高、一致性好、可复现、鲁棒性好等特点,逐渐成......
  • 【Algorithm算法章】递归&&搜索&&回溯&&算法思路总结概括
    文章目录......
  • 三、Web自动化测试(2)
    一、Pytest框架了解1.unittest:unittest是Python的内置测试框架,受到了Java中JUnit的启发。它提供了一个基于类的测试框架,鼓励使用面向对象的方法编写测试用例。通常,测试用例被组织在测试类中,并且测试类继承自unittest.TestCase类。测试方法的命名通常以test_开头。un......
  • 三、Web自动化测试(1)
    一、认识Web自动化首先看一下ChatGPT的解答:Web自动化测试涉及多个方面的知识和技能,包括以下内容:编程语言:通常使用Python、Java、JavaScript等编程语言进行自动化测试脚本的编写。掌握至少一种编程语言是必要的。Web开发技术:了解HTML、CSS、JavaScript等基本的Web......
  • centos7安装weblogic14
    Centos7安装weblogic 1、配置java环境weblogic运行依赖java环境,所以第一步先配置java环境上传、解压jdk安装包[root@bogon~]#rz-be[root@bogon~]#tar-zxvfjdk1.8.tar.gz配置java环境变量[root@bogon~]#vim/etc/profile exportJAVA_HOME=/opt/jdk1.8 exportCLASSPA......
  • Golang 实现Java的AES ECB 加密
    JavapublicstaticStringencryptAesEcb(Stringtarget,StringsKey)throwsException{byte[]raw=sKey.getBytes("UTF-8");//"AES"就是用AES/ECB/PKCS5PaddingSecretKeySpecskeySpec=newSecretKeySpec(raw,......
  • Chrome DevTools攻略:深入探索Web开发利器
    在现代Web开发中,ChromeDevTools(Chrome开发者工具)已经成为了不可或缺的利器之一。它是一个强大的Web开发工具集合,提供了各种功能和功能,帮助开发人员调试、优化和改进其网站和Web应用程序。本文将深入探讨ChromeDevTools的各项功能,并介绍如何利用这些功能提升Web开发效率和......