cmd/shrt/internal/base/base.go in go-shrt

at v0.4.1

1// See LICENSE file for copyright and license details
2
3// Package base defines the foundational structures required to build
4// out the Shrt command suite.
5package base
6
7import (
8 "context"
9 "flag"
10)
11
12// Environment variable keys
13const (
14 SHRTENV = "SHRTENV"
15 SHRT_SRVNAME = "SHRT_SRVNAME"
16 SHRT_SCMTYPE = "SHRT_SCMTYPE"
17 SHRT_SUFFIX = "SHRT_SUFFIX"
18 SHRT_RDRNAME = "SHRT_RDRNAME"
19 SHRT_BARERDR = "SHRT_BARERDR"
20 SHRT_DBPATH = "SHRT_DBPATH"
21 SHRT_GOSOURCEDIR = "SHRT_GOSOURCEDIR"
22 SHRT_GOSOURCEFILE = "SHRT_GOSOURCEFILE"
23)
24
25// KnownEnv is a list of environment variables that affect the
26// operation of the shrt command
27const KnownEnv = `
28 SHRTENV
29 SHRT_SRVNAME
30 SHRT_SCMTYPE
31 SHRT_SUFFIX
32 SHRT_RDRNAME
33 SHRT_BARERDR
34 SHRT_DBPATH
35 SHRT_GOSOURCEDIR
36 SHRT_GOSOURCEFILE
37 `
38
39type Command struct {
40 Run func(context.Context)
41 Flags flag.FlagSet
42 Name, ShortHelp, LongHelp, Usage string
43 Subcommands []*Command
44}
45
46var Shrt = &Command{
47 Name: "shrt",
48 LongHelp: `Shrt is a URL shortener and go-get redirector.
49
50Shrt is a URL shortener service (much like bit.ly without the
51trackers) that also handles go-get requests. The latter are a
52specific GET request query used by the Go programming language
53toolchain to aid in the downloading of utilities and libraries
54prior to build and installation.
55
56Upon invocation, shrt does one of two things depending
57on the presence or absence of the init argument. If the init
58argument is present, a series of questions is asked, the responses
59are recorded in a configuration file, and the program exits. If
60the init argument is absent, shrt reads the configuration and
61database files into memory, binds to the port specified by the
62-l flag, and begins serving requests.
63
64Shortlinks are recorded in the database, and any request path
65not matching a shortlink is assumed to be a go-get request. This
66is by design, but can result in specious redirects. Additionally,
67subdirectory paths are not allowed.
68
69Shortlinks generate an HTTP 301 response. Go-get requests generate
70an HTTP 200 response. If configured, requests to the base path
71(i.e., "/") generate an HTTP 302 response.
72
73In order to add a new shortlink to the database, simply edit the
74file. After saving, users on Unix systems may send SIGHUP to a
75running server process to reload the file. Non-Unix users will need
76to restart the server.
77`,
78 Usage: "shrt <command> [arguments]",
79}
80
81func FindCommand(cmd string) *Command {
82 for _, sub := range Shrt.Subcommands {
83 if sub.Name == cmd {
84 return sub
85 }
86 }
87 return nil
88}
89
90func (c *Command) Runnable() bool {
91 return c.Run != nil
92}