|
| 1 | +// Copyright 2014 The StudyGolang Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | +// http://studygolang.com |
| 5 | +// Author:polaris [email protected] |
| 6 | + |
| 7 | +/* |
| 8 | +Package version sets version information for the binary where it is imported. |
| 9 | +The version can be retrieved either from the -version command line argument, |
| 10 | +or from the /debug/version/ http endpoint. |
| 11 | +
|
| 12 | +To include in a project simply import the package and call version.Init(). |
| 13 | +
|
| 14 | +The version and compile date is stored in version and date variables and |
| 15 | +are supposed to be set during compile time. Typically this is done by the |
| 16 | +install(bash/bat). |
| 17 | +
|
| 18 | +To set these manually use -ldflags together with -X, like in this example: |
| 19 | +
|
| 20 | + go install -ldflags "-X util.version v1.0" |
| 21 | +
|
| 22 | +*/ |
| 23 | + |
| 24 | +package util |
| 25 | + |
| 26 | +import ( |
| 27 | + "flag" |
| 28 | + "fmt" |
| 29 | + "html" |
| 30 | + "io" |
| 31 | + "net/http" |
| 32 | + "os" |
| 33 | +) |
| 34 | + |
| 35 | +var showVersion = flag.Bool("version", false, "Print version of this binary (only valid if compiled with install(bash/bat))") |
| 36 | + |
| 37 | +var ( |
| 38 | + version string |
| 39 | + date string |
| 40 | +) |
| 41 | + |
| 42 | +func printVersion(w io.Writer, version string, date string) { |
| 43 | + fmt.Fprintf(w, "Version: %s\n", version) |
| 44 | + fmt.Fprintf(w, "Binary: %s\n", os.Args[0]) |
| 45 | + fmt.Fprintf(w, "Compile date: %s\n", date) |
| 46 | + fmt.Fprintf(w, "(version and date only valid if compiled with install(bash/bat))\n") |
| 47 | +} |
| 48 | + |
| 49 | +// initializes the version flag and /debug/version/ http endpoint. |
| 50 | +// Note that this method will call flag.Parse if the flags are not already parsed. |
| 51 | +func init() { |
| 52 | + if !flag.Parsed() { |
| 53 | + flag.Parse() |
| 54 | + } |
| 55 | + if showVersion != nil && *showVersion { |
| 56 | + printVersion(os.Stdout, version, date) |
| 57 | + os.Exit(0) |
| 58 | + } |
| 59 | + |
| 60 | + http.Handle("/version", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 61 | + printVersion(w, html.EscapeString(version), html.EscapeString(date)) |
| 62 | + })) |
| 63 | +} |
0 commit comments