首页 > 后端开发 > Golang > 正文

Golang框架在实际项目中的案例分享

WBOY
发布: 2024-07-15 18:21:02
原创
916人浏览过

go框架在实际项目中有着广泛的应用,包括以下场景:使用gin构建rest api;利用kubernetes打造微服务;运用cobra创建自定义命令行工具;使用分布式键值存储构建分布式系统。

Golang框架在实际项目中的案例分享

Go框架在实际项目中的案例分享

Go语言因其卓越的并发性、可扩展性和高性能而备受推崇,在开发各种应用程序时得到了广泛使用。本文将通过几个实战案例,展示Go框架在实际项目中的应用,涵盖Web服务、微服务、命令行工具和分布式系统等领域。

Web服务

使用Go框架创建Web服务是十分常见的。例如,使用Gin框架构建一个简单的REST API:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Welcome to my API!",
        })
    })
    r.Run() // 监听并服务HTTP请求
}
登录后复制

微服务

微服务架构在当今的软件开发中变得越来越普遍。利用Go的并发性和可扩展性,我们可以使用Kubernetes等编排工具,轻松创建和管理微服务。以下是一个使用Go和Kubernetes构建微服务的示例:

TP5实战_教学管理系统整站源码
TP5实战_教学管理系统整站源码

本套教程,以一个真实的学校教学管理系统为案例,手把手教会您如何在一张白纸上,从零开始,一步一步的用ThinkPHP5框架快速开发出一个商业项目,让您快速入门TP5项目开发。

TP5实战_教学管理系统整站源码 12518
查看详情 TP5实战_教学管理系统整站源码

立即学习go语言免费学习笔记(深入)”;

package main

import (
    "fmt"
    "net/http"
    "os"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        host, err := os.Hostname()
        if err != nil {
            http.Error(w, "Could not get hostname", http.StatusInternalServerError)
            return
        }
        fmt.Fprintf(w, "Hello from %s!", host)
    })

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    srv := &http.Server{
        Addr:    ":" + port,
        Handler: nil, // Use DefaultServeMux for root URL without prefix
        IdleTimeout:  60 * time.Second,
        ReadTimeout:   10 * time.Second,
        WriteTimeout:  30 * time.Second,
    }
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        fmt.Println(err)
    }
}
登录后复制

命令行工具

Go框架也非常适合构建命令行工具。例如,使用Cobra框架为Git提交创建自定义命令:

package main

import (
    "fmt"
    "log"

    "github.com/spf13/cobra"
)

func main() {
    commitCmd := &cobra.Command{
        Use:  "commit",
        Short: "Commits the current changes",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Committing changes...")
            // Perform commit logic here
        },
    }

    rootCmd := &cobra.Command{Use: "git-custom"}
    rootCmd.AddCommand(commitCmd)

    if err := rootCmd.Execute(); err != nil {
        log.Fatal(err)
    }
}
登录后复制

分布式系统

Go语言出色的并发性和健壮性使其成为构建分布式系统的理想选择。例如,使用Go实现分布式键值存储服务:

package main

import (
    "github.com/hashicorp/go-hclog"
    "github.com/hashicorp/raft"
    "github.com/hashicorp/raft-boltdb"
)

func main() {
    log := hclog.New(&hclog.LoggerOptions{
        Name:   "main",
        Level:  hclog.Error,
        Output: os.Stderr,
    })

    // Initialize Raft state
    config := raft.DefaultConfig()
    config.LocalID = raft.ServerID("server1")
    if len(os.Args) > 1 {
        config.LocalID = raft.ServerID(os.Args[1])
    }
    addr := os.Getenv("BIND_ADDR")
    if addr == "" {
        addr = "localhost:8080"
    }
    store, err := raftboltdb.NewBoltStore(fmt.Sprintf("%s.bolt", config.LocalID))
    if err != nil {
        log.Error("Failed to create storage", "error", err)
        os.Exit(1)
    }
    fsm := &fsm{}
    raft, err := raft.NewRaft(config, fsm, store, log)
    if err != nil {
        log.Error("Failed to create new Raft instance", "error", err)
        os.Exit(1)
    }

    raft.Start()
    defer func() {
        log.Debug("Shutting down Raft")
        raft.Shutdown()
    }()
    http.HandleFunc("/api/key", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case "GET":
            key := r.URL.Query().Get("key")
            if key == "" {
                http.Error(w, "key is required", http.StatusBadRequest)
                return
            }
            val, err := raft.Get([]byte(key))
            if err != nil {
                http.Error(w, "failed to get value", http.StatusInternalServerError)
                return
            }
            if val == nil {
                http.Error(w, "key not found", http.StatusNotFound)
                return
            }
            w.Write(val)
        case "PUT":
            key := r.URL.Query().Get("key")
            if key == "" {
                http.Error(w, "key is required", http.StatusBadRequest)
                return
            }
            val := r.FormValue("val")
            if val == "" {
                http.Error(w, "val is required", http.StatusBadRequest)
                return
            }
            cmd := raft.Request([]byte(key), []byte(val))
            if cmd == nil {
                http.Error(w, "failed to commit command", http.StatusInternalServerError)
                return
            }
            w.Write([]byte("OK"))
        case "DELETE":
            key := r.URL.Query().Get("key")
            if key == "" {
                http.Error(w, "key is required", http.StatusBadRequest)
                return
            }
            cmd := raft.Request([]byte(key), nil)
            if cmd == nil {
登录后复制

以上就是Golang框架在实际项目中的案例分享的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号