Print User input to physical printer in Golang - go

I'm new here in Golang world for a week.. I've been research and still don't know how to print from user input to physical printer, from USB to printer.
For example I have done with code, just need add other function to print..
package main
import "fmt"
func main() {
fmt.Println("First name: ")
var name1 string
fmt.Scanln(&name1)
)
fmt.Println("Last name: ")
var name2 string
fmt.Scanln(&name2)
fmt.Print("My full name is: ")
fmt.Print(name1 + " " + name2)
}
func print(){
//need function to print directly from USB to pyhsical printer..
//print from func main() as text, any format
}
I have no idea to create print func in golang from user input..
If successful, then after func main() println, then immediately send the command to print to my printer.. just using terminal, I don't need the GUI.
Thank you for helping me:')

Related

Generated valid label value (Kubernetes)

Label values in Kubernetes need to be valid.
See IsValidLabelValue()
For example the input I receive from a rest-API of a provider, which I want to write to a label: Dedicated Server 1U.
Is there a way to generate a valid label via Go from an arbitrary string?
you can have a function to do this, for example:
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
return "api-label=" + input
}
the function replaces the spaces in the received string to "-"
you can change the key to any string you like.
you can also add a regex check to make sure that the generated value complies with the label constraints. (this depends if any special characters are being received from the API)
To accept the string even when there are unwanted characters, check the below:
package main
import (
"regexp"
"strings"
"fmt"
)
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
re := regexp.MustCompile("[^a-zA-Z0-9-]")
input = re.ReplaceAllString(input, "")
re = regexp.MustCompile("^[^a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?$")
input = re.ReplaceAllString(input, "")
return "api-label=" + input
}
func main() {
label := generateLabel("Dedicated Server 1U")
fmt.Println(label) // Output: "api-label=Dedicated-Server-1U"
label1 := generateLabel("Dedicated&test")
fmt.Println(label1) // Output: "api-label=Dedicatedtest"
label2 := generateLabel("Dedicated,test##&(*!great")
fmt.Println(label2) // Output: "api-label=Dedicatedtestgreat"
}

Strange performing of map data type

I am trying to add a bunch of values in a map data type and after that trying to print it out. But it is performing strangely. When I am directly calling the map with the key it is giving me the correct output but not giving me any output when I am storing the key in a variable and then calling it. I am not been able to figure it out what is happening and why am I getting this kind of output. Can Somebody help me with the same.
package main
import (
"bufio"
"fmt"
"os"
)
func main(){
type Authentication struct {
password string
}
var authentication = map[string]Authentication{}
var user1 Authentication
user1.password = "abc"
authentication["def"] = user1
reader := bufio.NewReader(os.Stdin)
usid := readString(reader)
fmt.Println(authentication)
fmt.Println(authentication[usid])
fmt.Println(authentication["def"])
}
// Reading input functions
func readString(reader *bufio.Reader) string {
s, _ := reader.ReadString('\n')
for i := 0; i < len(s); i++ {
if s[i] == '\n' {
return s[:i]
}
}
return s
}
Input:
def
Output:
map[def:{abc}]
{abc}
You're trying to do the same thing twice in readString. But all you have to do is to cut it by one byte.
func readString(reader *bufio.Reader) string {
s, _ := reader.ReadString('\n')
return s[:len(s)-1]
}
The program in the question does not work when \r\n is used as the line terminator in stdin. The program removes the trailing \n from the line, but not the \r.
Fix by using bufio.Scanner instead of bufio.Reader to read lines from the input. The bufio.Scanner type removes line terminators.
func main() {
type Authentication struct {
password string
}
var authentication = map[string]Authentication{}
var user1 Authentication
user1.password = "abc"
authentication["def"] = user1
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
log.Fatal(scanner.Err())
}
usid := scanner.Text()
fmt.Println(authentication)
fmt.Println(authentication[usid])
fmt.Println(authentication["def"])
}
There can always be a better way of reading string, but I see your code works too. I ran it in my local and it gives the expected output:
From your description, I presume you are using go playground or any such platform. If that is so, the thing is, go playground doesn't take standard input, and your code has reader on os.Stdin. When I copy your code to playground and add the following line to check,
fmt.Printf("Length of usid: %d\nusid: %q\n", len(usid), usid)
I see the following output:
Length of usid: 0
usid: ""
Conclusion: There is no issue with variables, map or code, but just the stdin.

Go program not waiting for input with scanf

I've found some sort of similar problems in c, but the solutions are c specific. package main
Here is a minimum working example of the code
import "fmt"
func main() {
var mode string
var base int
for {
fmt.Printf("(Base) [-->]: ")
fmt.Scanf("%d", &base)
fmt.Printf("(Mode) [-->]: ")
fmt.Scanf("%s", &mode)
}
}
My issue is that after asking for the mode input, it doesn't wait for input, and immediately skips to the beginning of the loop. Something like this:
(Base) [-->]: 5
(Mode) [-->]: (Base) [-->]:
I had the same problem, changefmt.Scanf("%d", &base) to fmt.Scanf("%d \n", &base). I think it's connected to output of Scanf() where extra newline not being consumed by first scanf. Above code may still work in some device without any errors.
import "fmt"
func main() {
var mode string
var base int
for {
fmt.Printf("(Base) [-->]: ")
fmt.Scanf("%d \n", &base)
fmt.Printf("(Mode) [-->]: ")
fmt.Scanf("%s \n", &mode)
}
}

Why is second scanf being skipped over?

I decided to take a look at Go and I am currently stuck on something. In this program, I am asking the user to choose option 1 or 2. If option 1 is chosen, I want the ReadAppList function to ask the user for a last name.
It seems as if the second scanf is being skipped over and not allowing the user to enter a last name. Is it only reading the first user input?
package main
import (
"fmt"
)
// Main function that runs on startup
func main() {
fmt.Println("\n1. Search Last Name ")
fmt.Println("\n2. Exit ")
fmt.Println("\nPick an option: ")
var userAnswer int
fmt.Scanf("%d", &userAnswer)
if userAnswer == 1 {
ReadAppsList()
} else if userAnswer == 2 {
fmt.Println("\nGoodbye.")
} else {
fmt.Println("\nThat is not a valid choice.")
}
}
func ReadAppsList() {
fmt.Println("\nType your LastName of the person you want to look up: ")
var lastName string
fmt.Scanf("%s", &lastName)
fmt.Sprintf("You typed %s", lastName)
}
That's because extra newline not being consumed by first scanf.
Change your scanf to this fmt.Scanf("%d\n", &userAnswer).
In your ReadAppsList you have:
fmt.Sprintf("You typed %s", lastName)
The problem is that Sprintf returns a string without writing to the screen. Change that to Printf and it'll print the lastname.
The Scanf for the last name is happening as you'd expect.

Convert data to base64 encode in go

I am new to go programming language and I'm stock on this scenario on my code.
Here's my example code:
a := genreAPI{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println("Value of a :", a)
The current output is: Value of a : [{Pop} {Rock}]
How can I achieved an output like this:
Value of a : [{UG9w} {Um9jaw==}]
which is a base64 encode?
I am not sure what exactly is not clear from the documentation. Not only it has a clear name which explains states what the method is doing, it also has an example.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("Pop")
str := base64.StdEncoding.EncodeToString(data)
fmt.Println(str) // UG9w
}
Go Playground
You can customise the output of print functions by providing a String() method for your type. Either for the whole Genre or just for the name variable.
Example:
package main
import (
"encoding/base64"
"fmt"
)
type Base64String string
func (b Base64String) String() string {
return base64.StdEncoding.EncodeToString([]byte(b))
}
type Genre struct {
Name Base64String
}
func main() {
a := []Genre{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println(a) // prints [{UG9w} {Um9jaw==}]
fmt.Println(string(a[0].Name)) // prints Pop
}

Resources