dongying195959 2018-01-18 11:30
浏览 6

全局变量不能从CLI命令中保留

package main

import (
    "fmt"
    "net/http"
    "os"
    "strconv"

    "github.com/go-chi/chi"
)

var tests []string

func main() {

    if len(os.Args[:]) > 1 {
        tests = append(tests, "test")
        fmt.Println(strconv.Itoa(len(tests)) + " tests")
        os.Exit(0)
    }

    r := chi.NewRouter()
    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        tests = append(tests, "test")
        fmt.Println(strconv.Itoa(len(tests)) + " tests")
    })

    http.ListenAndServe(":8086", r)
}

When i access the program from localhost:8086 it works okay and i can see len(tests) increment when i refresh.

But when i access the program with ./test arg command, len(tests) increments to 1 but then gets lost, so next time it says 1 and never goes any higher.

I thought that these two methods should also share the same tests value, but when i write to one, the other can't read it etc.

Thanks.

  • 写回答

1条回答 默认 最新

  • drgbpq5930 2018-01-18 11:32
    关注

    tests is a global variable. As long as your process is running, it will keep its value.

    However, when you run ./test arg, this starts a new process, adds an element to tests, then exits. The next invocation of ./test arg is a completely new process, it has no way of sharing information with the previous invocation.

    The process running with ./test arg is also completely different from the currently-running web server started with ./test. Same thing: they share no state, they just happen to be the same binary.

    If you want to persist something between invocations of a given program, you need to save the data somewhere (file, database, etc...).

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b