0% found this document useful (0 votes)
10 views

Network Programming with Go Language : Essential Skills for Programming, Using and Securing Networks with Open Source Google Golang 2nd Edition Jan Newmarch pdf download

The document provides information about the book 'Network Programming with Go Language: Essential Skills for Programming, Using and Securing Networks with Open Source Google Golang, 2nd Edition' by Jan Newmarch and Ronald Petty. It highlights the book's focus on Go programming language, its updates reflecting the latest version, and its aim to teach networking concepts using Go. Additionally, it includes links to download the book and other related resources.

Uploaded by

habobtkiadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Network Programming with Go Language : Essential Skills for Programming, Using and Securing Networks with Open Source Google Golang 2nd Edition Jan Newmarch pdf download

The document provides information about the book 'Network Programming with Go Language: Essential Skills for Programming, Using and Securing Networks with Open Source Google Golang, 2nd Edition' by Jan Newmarch and Ronald Petty. It highlights the book's focus on Go programming language, its updates reflecting the latest version, and its aim to teach networking concepts using Go. Additionally, it includes links to download the book and other related resources.

Uploaded by

habobtkiadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Network Programming with Go Language : Essential

Skills for Programming, Using and Securing


Networks with Open Source Google Golang 2nd
Edition Jan Newmarch pdf download
https://ebookmeta.com/product/network-programming-with-go-
language-essential-skills-for-programming-using-and-securing-
networks-with-open-source-google-golang-2nd-edition-jan-newmarch/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Network Programming with Go Language : Essential Skills


for Programming, Using and Securing Networks with Open
Source Google Golang 2nd Edition Jan Newmarch

https://ebookmeta.com/product/network-programming-with-go-
language-essential-skills-for-programming-using-and-securing-
networks-with-open-source-google-golang-2nd-edition-jan-newmarch/

Network Programming with Go Language 2nd Edition Ronald


Petty

https://ebookmeta.com/product/network-programming-with-go-
language-2nd-edition-ronald-petty/

Software Development with Go: Cloud-Native Programming


using Golang with Linux and Docker Nanik Tolaram

https://ebookmeta.com/product/software-development-with-go-cloud-
native-programming-using-golang-with-linux-and-docker-nanik-
tolaram/

Anoikis How the Extracellular Matrix Regulates Life or


Death Decisions 1st Edition Steven M. Frisch

https://ebookmeta.com/product/anoikis-how-the-extracellular-
matrix-regulates-life-or-death-decisions-1st-edition-steven-m-
frisch/
IoT, Machine learning and Blockchain Technologies for
Renewable Energy and Modern Hybrid Power Systems 1st
Edition C. Sharmeela

https://ebookmeta.com/product/iot-machine-learning-and-
blockchain-technologies-for-renewable-energy-and-modern-hybrid-
power-systems-1st-edition-c-sharmeela/

National Geographic Traveler Florence and Tuscany 3rd


Edition Tim Jepson

https://ebookmeta.com/product/national-geographic-traveler-
florence-and-tuscany-3rd-edition-tim-jepson/

Fates and Furies Lauren Groff

https://ebookmeta.com/product/fates-and-furies-lauren-groff/

Mountain Daddy's Milk & Honeymoon (Spice in the


Mountains Book 2) 1st Edition Elena Dawne

https://ebookmeta.com/product/mountain-daddys-milk-honeymoon-
spice-in-the-mountains-book-2-1st-edition-elena-dawne/

The Bastard Complete Series 1st Edition Jack Porter

https://ebookmeta.com/product/the-bastard-complete-series-1st-
edition-jack-porter/
Forming Humanity Redeeming the German Bildung Tradition
1st Edition Jennifer A. Herdt

https://ebookmeta.com/product/forming-humanity-redeeming-the-
german-bildung-tradition-1st-edition-jennifer-a-herdt/
Jan Newmarch and Ronald Petty

Network Programming with Go


Language
Essential Skills for Programming, Using and
Securing Networks with Open Source Google
Golang
2nd ed.
Dr. Jan Newmarch
Oakleigh, VIC, Australia

Ronald Petty
San Francisco, CA, USA

ISBN 978-1-4842-8094-2 e-ISBN 978-1-4842-8095-9


https://doi.org/10.1007/978-1-4842-8095-9

© Jan Newmarch and Ronald Petty 2022

This work is subject to copyright. All rights are reserved by the


Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other
physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
I dedicate this to my family.
Preface to the Second Edition
While an age has passed in Internet years, Go remains a primary
destination for programmers. Go conquered the container technology
space. It continues to find affection in Cloud Native development. Go
strives to remain true to itself, backward compatible, yet adding new
language features like Generics. Tooling improvements such as Fuzzing
allow for more secure application development.
Go has changed, and so has this book. The first edition used Go 1.8;
we are now on Go 1.18. The code has been updated to reflect this new
reality. The examples have been largely developed to show a particular
feature of Go networking without forcing complexity like managing
several projects or packages scattered across the book; the associated
repository can be found here
https://github.com/Apress/network-prog-with-go-2e.
The first version of this book assumed familiarity with Go, and that
remains in this edition. We expand slightly what we are willing to
discuss in this book with the inclusion of more third-party modules,
tools, and techniques. Jan was correct to keep the focus on Go and not
to be distracted with the ecosystem at large.
If you desire to learn about implementing networking concepts with
Go, I hope this book serves you well.
As a point of comparison, what follows is Jan’s original preface,
reflecting Go in 2017.
Preface to the First Edition
It’s always fun to learn a new programming language, especially when it
turns out to be a major one. Prior to the release of Go in 2009, I was
teaching a Master’s level subject in network programming at Monash
University. It’s good to have a goal when learning a new language, but
this time, instead of building yet another wine cellar program, I decided
to orient my lecture notes around Go instead of my (then) standard
delivery vehicle of Java.
The experiment worked well: apart from the richness of the Java
libraries that Go was yet to match, all the programming examples
transferred remarkably well, and in many cases were more elegant than
the original Java programs.
This book is the result. I have updated it as Go has evolved and as
new technologies such as HTTP/2 have arisen. But if it reads like a
textbook, well, that is because it is one. There is a large body of
theoretical and practical concepts involved in network programming
and this book covers some of these as well as the practicalities of
building systems in Go.
In terms of language popularity, Go is clearly rising. It has climbed
to 16th in the TIOBE index, is 18th in the PYPL (Popularity of
Programming Language), and is 15th in the RedMonk Programming
Language rankings. It is generally rated as one of the fastest growing
languages.
There is a growing community of developers both of the core
language and libraries and of the independent projects. I have tried to
limit the scope of this book to the standard libraries only and to the
“sub-repositories” of the Go tree. While this eliminates many excellent
projects that no doubt make many programming tasks easier,
restricting the book to the official Go libraries provides a clear bound.
This book assumes a basic knowledge of Go. The focus is on using
Go to build network applications, not on the basics of the language.
Network applications are different than command-line applications, are
different than applications with a graphical user interface, and so on. So
the first chapter discusses architectural aspects of network programs.
The second chapter is an overview of the features of Go that we use in
this book. The third chapter on sockets covers the Go version of the
basics underlying all TCP/IP systems. Chapters 4, 5, and 6 are more
unusual in network programming books. They cover the topics of what
representations of data will be used, how a network interaction will
proceed, and for text, which language formats are used. Then in Chapter
7, we look at the increasingly important topic of security. In Chapter 8,
we look at one of the most common application layer protocols in use,
HTTP. The next four chapters are about topics related to HTTP and
common data formats carried above HTTP – HTML and XML. In
Chapter 13, we look at an alternative approach to network
programming, remote procedure calls. Chapters 14 and 15 consider
further aspects of network programming using HTTP.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub. For more detailed
information, please visit
https://github.com/Apress/network-prog-with-go-2e.
Acknowledgments
I want to share my appreciation for Jan Newmarch for collaborating on
this book. This project has offered me a tremendous sense of
achievement and allowed me to cross a much-anticipated item off my
bucket list. I would also like to thank Eldon Alameda for his thoughtful
approach at letting me know when I am off the mark and for providing
me with solid advice.
Additionally, I owe gratitude to my partners at Apress, both Steve
Anglin for the opportunity and Mark Powers for the guidance to help
see this through. Thank you to my colleagues at RX-M, including Randy
Abernethy, Christopher Hanson, Andrew Bassett, and Anita Wu. Our
work over the years has allowed for my participation in a project such
as this book.
Finally, I want to thank my wife Julie and daughter Charlotte. Julie’s
capacity to manage the world while I hide out on a computer is
unmatched and most appreciated. Charlotte’s energy, abilities, and
creativity inspire me to become better every day.

—Ronald Petty
Table of Contents
Chapter 1:​Architectural Layers
Protocol Layers
ISO OSI Protocol
OSI Layers
TCP/​IP Protocol
Some Alternative Protocols
Networking
Gateways
Host-Level Networking
Packet Encapsulation
Connection Models
Connection Oriented
Connectionless
Communications Models
Message Passing
Remote Procedure Call
Distributed Computing Models
Client-Server System
Client-Server Application
Server Distribution
Communication Flows
Synchronous Communication
Asynchronous Communication
Streaming Communication
Publish/​Subscribe
Component Distribution
Gartner Classification
Three-Tier Models
Fat vs.​Thin
Middleware Model
Middleware Examples
Middleware Functions
Continuum of Processing
Points of Failure
Acceptance Factors
Thoughts on Distributed Computing
Transparency
Access Transparency
Location Transparency
Migration Transparency
Replication Transparency
Concurrency Transparency
Scalability Transparency
Performance Transparency
Failure Transparency
Eight Fallacies of Distributed Computing
Fallacy: The Network Is Reliable
Fallacy: Latency Is Zero
Fallacy: Bandwidth Is Infinite
Fallacy: The Network Is Secure
Fallacy: Topology Doesn’t Change
Fallacy: There Is One Administrator
Fallacy: Transport Cost Is Zero
Fallacy: The Network Is Homogeneous
Conclusion
Chapter 2:​Overview of the Go Language
Types
Slices and Arrays
Maps
Pointers
Functions
Structures
Methods
Multithreading
Packages
Modules
Type Conversion
Statements
GOPATH
Running Go Programs
Standard Libraries
Error Values
Conclusion
Chapter 3:​Socket-Level Programming
The TCP/​IP Stack
IP Datagrams
UDP
TCP
Internet Addresses
IPv4 Addresses
IPv6 Addresses
IP Address Type
Using Available Documentation and Examples
The IPMask Type
Basic Routing
The IPAddr Type
Host Canonical Name and Addresses Lookup
Services
Ports
The TCPAddr Type
TCP Sockets
TCP Client
A Daytime Server
Multithreaded Server
Controlling TCP Connections
Timeout
Staying Alive
UDP Datagrams
Server Listening on Multiple Sockets
The Conn, PacketConn, and Listener Types
Raw Sockets and the IPConn Type
Conclusion
Chapter 4:​Data Serialization
Structured Data
Mutual Agreement
Self-Describing Data
Encoding Packages
ASN.​1
ASN.​1 Daytime Client and Server
JSON
A Client and A Server
The Gob Package
A Client and A Server
Encoding Binary Data As Strings
Protocol Buffers
Installing and Compiling Protocol Buffers
The Generated personv3.​pb.​go File
Using the Generated Code
Conclusion
Chapter 5:​Application-Level Protocols
Protocol Design
Why Should You Worry?​
Version Control
The Web
Message Format
Data Format
Byte Format
Character Format
A Simple Example
Discovering Diverse Content Through
Random Scribd Documents
remembered such an abandoned creature, on occasions when it
would otherwise have had no eyes, or would have closed them. The
lack of power to hold his tongue concerning the common secret, and
the irresponsible tendency to see what no one wishes to see—
himself—brought him to a prison and an early death.

66.
Punishable, But Never Punished.—Our crime against criminals lies in the
fact that we treat them like rascals.

67.
Sancta Simplicitas OF VIRTUE.—Every virtue has its privileges; for
example, that of contributing its own little faggot to the scaffold of
every condemned man.

68.
Morality and Consequences.—It is not only the spectators of a deed
who frequently judge of its morality or immorality according to its
consequences, but the doer of the deed himself does so. For the
motives and intentions are seldom sufficiently clear and simple, and
sometimes memory itself seems clouded by the consequences of the
deed, so that one ascribes the deed to false motives or looks upon
unessential motives as essential. Success often gives an action the
whole honest glamour of a good conscience; failure casts the
shadow of remorse over the most estimable deed. Hence arises the
well-known practice of the politician, who thinks, "Only grant me
success, with that I bring all honest souls over to my side and make
myself honest in my own eyes." In the same way success must
replace a better argument. Many educated people still believe that
the triumph of Christianity over Greek philosophy is a proof of the
greater truthfulness of the former,—although in this case it is only
the coarser and more powerful that has triumphed over the more
spiritual and delicate. Which possesses the greater truth may be
seen from the fact that the awakening sciences have agreed with
Epicurus' philosophy on point after point, but on point after point
have rejected Christianity.

69.
Love and Justice.—Why do we over-estimate love to the disadvantage
of justice, and say the most beautiful things about it, as if it were
something very much higher than the latter? Is it not visibly more
stupid than justice? Certainly, but precisely for that reason all the
pleasanter for every one. It is blind, and possesses an abundant
cornucopia, out of which it distributes its gifts to all, even if they do
not deserve them, even if they express no thanks for them. It is as
impartial as the rain, which, according to the Bible and experience,
makes not only the unjust, but also occasionally the just wet through
to the skin.

70.
Execution.—How is it that every execution offends us more than does
a murder? It is the coldness of the judges, the painful preparations,
the conviction that a human being is here being used as a warning
to scare others. For the guilt is not punished, even if it existed—it
lies with educators, parents, surroundings, in ourselves, not in the
murderer—I mean the determining circumstances.

71.
Hope.—Pandora brought the box of ills and opened it. It was the gift
of the gods to men, outwardly a beautiful and seductive gift, and
called the Casket of Happiness. Out of it flew all the evils, living
winged creatures, thence they now circulate and do men injury day
and night. One single evil had not yet escaped from the box, and by
the will of Zeus Pandora closed the lid and it remained within. Now
for ever man has the casket of happiness in his house and thinks he
holds a great treasure; it is at his disposal, he stretches out his hand
for it whenever he desires; for he does not know the box which
Pandora brought was the casket of evil, and he believes the ill which
remains within to be the greatest blessing,—it is hope. Zeus did not
wish man, however much he might be tormented by the other evils,
to fling away his life, but to go on letting himself be tormented again
and again. Therefore he gives man hope,—in reality it is the worst of
all evils, because it prolongs the torments of man.

72.
The Degree of Moral Inflammability Unknown.—According to whether we
have or have not had certain disturbing views and impressions—for
instance, an unjustly executed, killed, or martered father; a faithless
wife; a cruel hostile attack—it depends whether our passions reach
fever heat and influence our whole life or not. No one knows to what
he may be driven by circumstances, pity, or indignation; he does not
know the degree of his own inflammability. Miserable little
circumstances make us miserable; it is generally not the quantity of
experiences, but their quality, on which lower and higher man
depends, in good and evil.

73.
The Martyr in Spite of Himself.—There was a man belonging to a party
who was too nervous and cowardly ever to contradict his comrades;
they made use of him for everything, they demanded everything
from him, because he was more afraid of the bad opinion of his
companions than of death itself; his was a miserable, feeble soul.
They recognised this, and on the ground of these qualities they
made a hero of him, and finally even a martyr. Although the coward
inwardly always said No, with his lips he always said Yes, even on
the scaffold, when he was about to die for the opinions of his party;
for beside him stood one of his old companions, who so tyrannised
over him by word and look that he really suffered death in the most
respectable manner, and has ever since been celebrated as a martyr
and a great character.

74.
I the Every-day Standard.—One will seldom go wrong if one attributes
extreme actions to vanity, average ones to habit, and petty ones to
fear.

75.
Misunderstanding Concerning Virtue.—Whoever has known immorality
in connection with pleasure, as is the case with a man who has a
pleasure-seeking youth behind him, imagines that virtue must be
connected with absence of pleasure.—Whoever, on the contrary, has
been much plagued by his passions and vices, longs to find in virtue
peace and the soul's happiness. Hence it is possible for two virtuous
persons not to understand each other at all.

76.
The Ascetic.—The ascetic makes a necessity of virtue.

77.
Transferring Honour from the Person to the Thing.—Deeds of love and
sacrifice for the benefit of one's neighbour are generally honoured,
wherever they are manifested. Thereby we multiply the valuation of
things which are thus loved, or for which we sacrifice ourselves,
although perhaps they are not worth much in themselves. A brave
army is convinced of the cause for which it fights.

78.
Ambition a Substitute For the Moral Sense.—The moral sense must not
be lacking in those natures which have no ambition. The ambitious
manage without it, with almost the same results. For this reason the
sons of unpretentious, unambitious families, when once they lose
the moral sense, generally degenerate very quickly into complete
scamps.

79.
Vanity Enriches.—How poor would be the human mind without vanity!
Thus, however, it resembles a well-stocked and constantly
replenished bazaar which attracts buyers of every kind. There they
can find almost everything, obtain almost everything, provided that
they bring the right sort of coin, namely admiration.

80.
Old Age and Death.—Apart from the commands of religion, the
question may well be asked, Why is it more worthy for an old man
who feels his powers decline, to await his slow exhaustion and
extinction than with full consciousness to set a limit to his life?
Suicide in this case is a perfectly natural, obvious action, which
should justly arouse respect as a triumph of reason, and did arouse
it in those times when the heads of Greek philosophy and the
sturdiest patriots used to seek death through suicide. The seeking,
on the contrary, to prolong existence from day to day, with anxious
consultation of doctors and painful mode of living, without the power
of drawing nearer to the actual aim of life, is far less worthy. Religion
is rich in excuses to reply to the demand for suicide, and thus it
ingratiates itself with those who wish to cling to life.

81.
Errors of the Sufferer and the Doer.—When a rich man deprives a
poor man of a possession (for instance, a prince taking the
sweetheart of a plebeian), an error arises in the mind of the poor
man; he thinks that the rich man must be utterly infamous to take
away from him the little that he has. But the rich man does not
estimate so highly the value of a single possession, because he is
accustomed to have many; hence he cannot imagine himself in the
poor man's place, and does not commit nearly so great a wrong as
the latter supposes. They each have a mistaken idea of the other.
The injustice of the powerful, which, more than anything else,
rouses indignation in history, is by no means so great as it appears.
Alone the mere inherited consciousness of being a higher creation,
with higher claims, produces a cold temperament, and leaves the
conscience quiet; we all of us feel no injustice when the difference is
very great between ourselves and another creature, and kill a fly, for
instance, without any pricks of conscience. Therefore it was no sign
of badness in Xerxes (whom even all Greeks describe as
superlatively noble) when he took a son away from his father and
had him cut in pieces, because he had expressed a nervous,
ominous distrust of the whole campaign; in this case the individual is
put out of the way like an unpleasant insect; he is too lowly to be
allowed any longer to cause annoyance to a ruler of the world. Yes,
every cruel man is not so cruel as the ill-treated one imagines the
idea of pain is not the same as its endurance. It is the same thing in
the case of unjust judges, of the journalist who leads public opinion
astray by small dishonesties. In all these cases cause and effect are
surrounded by entirely different groups of feelings and thoughts; yet
one unconsciously takes it for granted that doer and sufferer think
and feel alike, and according to this supposition we measure the
guilt of the one by the pain of the other.

82.
The Skin of the Soul.—As the bones, flesh, entrails, and blood-vessels
are enclosed within a skin, which makes the aspect of man
endurable, so the emotions and passions of the soul are enwrapped
with vanity,—it is the skin of the soul.
83.
The Sleep of Virtue.—When virtue has slept, it will arise again all the
fresher.

84.
The Refinement of Shame.—People are not ashamed to think something
foul, but they are ashamed when they think these foul thoughts are
attributed to them.

85.
Malice Is Rare.—Most people are far too much occupied with
themselves to be malicious.

86.
The Tongue in the Balance.—We praise or blame according as the one
or the other affords more opportunity for exhibiting our power of
judgment.

87.
St. Luke Xviii. 14, Improved.—He that humbleth himself wishes to be
exalted.

88.
The Prevention of Suicide.—There is a certain right by which we may
deprive a man of life, but none by which we may deprive him of
death; this is mere cruelty.

89.
Vanity.—We care for the good opinion of men, firstly because they
are useful to us, and then because we wish to please them (children
their parents, pupils their teachers, and well-meaning people
generally their fellow-men). Only where the good opinion of men is
of importance to some one, apart from the advantage thereof or his
wish to please, can we speak of vanity. In this case the man wishes
to please himself, but at the expense of his fellow-men, either by
misleading them into holding a false opinion about him, or by aiming
at a degree of "good opinion" which must be painful to every one
else (by arousing envy). The individual usually wishes to corroborate
the opinion he holds of himself by the opinion of others, and to
strengthen it in his own eyes; but the strong habit of authority—a
habit as old as man himself —induces many to support by authority
their belief in themselves: that is to say, they accept it first from
others; they trust the judgment of others more than their own. The
interest in himself, the wish to please himself, attains to such a
height in a vain man that he misleads others into having a false, all
too elevated estimation of him, and yet nevertheless sets store by
their authority,—thus causing an error and yet believing in it. It must
be confessed, therefore, that vain people do not wish to please
others so much as themselves, and that they go so far therein as to
neglect their advantage, for they often endeavour to prejudice their
fellow-men unfavourably, inimicably, enviously, consequently
injuriously against themselves, merely in order to have pleasure in
themselves, personal pleasure.

90.
The Limits of Human Love.—A man who has declared that another is an
idiot and a bad companion, is angry when the latter eventually
proves himself to be otherwise.

91.
Moralité Larmoyante.—What a great deal of pleasure morality gives!
Only think what a sea of pleasant tears has been shed over
descriptions of noble and unselfish deeds! This charm of life would
vanish if the belief in absolute irresponsibility were to obtain
supremacy.

92.
The Origin of Justice.—Justice (equity) has, its origin amongst powers
which are fairly equal, as Thucydides (in the terrible dialogue
between the Athenian and Melian ambassadors) rightly
comprehended: that is to say, where there is no clearly recognisable
supremacy, and where a conflict would be useless and would injure
both sides, there arises the thought of coming to an understanding
and settling the opposing claims; the character of exchange is the
primary character of justice. Each party satisfies the other, as each
obtains what he values more than the other. Each one receives that
which he desires, as his own henceforth, and whatever is desired is
received in return. Justice, therefore, is recompense and exchange
based on the hypothesis of a fairly equal degree of power,—thus,
originally, revenge belongs to the province of justice, it is an
exchange. Also gratitude.—Justice naturally is based on the point of
view of a judicious self-preservation, on the egoism, therefore, of
that reflection, "Why should I injure myself uselessly and perhaps
not attain my aim after all?" So much about the origin of justice.
Because man, according to his intellectual custom, has forgotten the
original purpose of so-called just and reasonable actions, and
particularly because for hundreds of years children have been taught
to admire and imitate such actions, the idea has gradually arisen
that such an action is un-egoistic; upon this idea, however, is based
the high estimation in which it is held: which, moreover, like all
valuations, is constantly growing, for something that is valued highly
is striven after, imitated, multiplied, and increases, because the value
of the output of toil and enthusiasm of each individual is added to
the value of the thing itself. How little moral would the world look
without this forgetfulness! A poet might say that God had placed
forgetfulness as door-keeper in the temple of human dignity.

93.
The Right of the Weaker.—When any one submits under certain
conditions to a greater power, as a besieged town for instance, the
counter-condition is that one can destroy one's self, burn the town,
and so cause the mighty one a great loss. Therefore there is a kind
of equalisation here, on the basis of which rights may be
determined. The enemy has his advantage in maintaining it. In so
far there are also rights between slaves and masters, that is,
precisely so far as the possession of the slave is useful and
important to his master. The right originally extends so far as one
appears to be valuable to the other, essentially unlosable,
unconquerable, and so forth. In so far the weaker one also has
rights, but lesser ones. Hence the famous unusquisque tantum juris
habet, quantum potentia valet (or more exactly, quantum potentia
valere creditur).

94.
The Three Phases of Hitherto Existing Morality.—It is the first sign that
the animal has become man when its actions no longer have regard
only to momentary welfare, but to what is enduring, when it grows
useful and practical; there the free rule of reason first breaks out. A
still higher step is reached when he acts according to the principle of
honour by this means he brings himself into order, submits to
common feelings, and that exalts him still higher over the phase in
which he was led only by the idea of usefulness from a personal
point of view; he respects and wishes to be respected, i.e. he
understands usefulness as dependent upon what he thinks of others
and what others think of him. Eventually he acts, on the highest step
of the hitherto existing—morality, according to his standard of things
and men; he himself decides for himself and others what is
honourable, what is useful; he has become the law-giver of opinions,
in accordance with the ever more highly developed idea of what is
useful and honourable. Knowledge enables him to place that which
is most useful, that is to say the general, enduring usefulness, above
the personal, the honourable recognition of general, enduring
validity above the momentary; he lives and acts as a collective
individual.

95.
The Morality of the Mature Individual.—The impersonal has hitherto
been looked upon as the actual distinguishing mark of moral action;
and it has been pointed out that in the beginning it was in
consideration of the common good that all impersonal actions were
praised and distinguished. Is not an important change in these views
impending, now when it is more and more recognised that it is
precisely in the most personal possible considerations that the
common good is the greatest, so that a strictly personal action now
best illustrates the present idea of morality, as utility for the mass?
To make a whole personality out of ourselves, and in all that we do
to keep that personality's highest good in view, carries us further
than those sympathetic emotions and actions for the benefit of
others. We all still suffer, certainly, from the too small consideration
of the personal in us; it is badly developed,—let us admit it; rather
has our mind been forcibly drawn away from it and offered as a
sacrifice to the State, to science, or to those who stand in need of
help, as if it were the bad part which must be sacrificed. We are still
willing to work for our fellow-men, but only so far as we find our
own greatest advantage in this work, no more and no less. It is only
a question of what we understand as our advantage; the unripe,
undeveloped, crude individual will understand it in the crudest way.

96.
Custom and Morality.—To be moral, correct, and virtuous is to be
obedient to an old-established law and custom. Whether we submit
with difficulty or willingly is immaterial, enough that we do so. He is
called "good" who, as if naturally, after long precedent, easily and
willingly, therefore, does what is right, according to whatever this
may be (as, for instance, taking revenge, if to take revenge be
considered as right, as amongst the ancient Greeks). He is called
good because he is good "for something"; but as goodwill, pity,
consideration, moderation, and such like, have come, with the
change in manners, to be looked upon as "good for something," as
useful, the good-natured and helpful have, later on, come to be
distinguished specially as "good." (In the beginning other and more
important kinds of usefulness stood in the foreground.) To be evil is
to be "not moral" (immoral), to be immoral is to be in opposition to
tradition, however sensible or stupid it may be; injury to the
community (the "neighbour" being understood thereby) has,
however, been looked upon by the social laws of all different ages as
being eminently the actual "immorality," so that now at the word
"evil" we immediately think of voluntary injury to one's neighbour.
The fundamental antithesis which has taught man the distinction
between moral and immoral, between good and evil, is not the
"egoistic" and "un-egoistic," but the being bound to the tradition,
law, and solution thereof. How the tradition has arisen is immaterial,
at all events without regard to good and evil or any immanent
categorical imperative, but above all for the purpose of preserving a
community, a generation, an association, a people; every
superstitious custom that has arisen on account of some falsely
explained accident, creates a tradition, which it is moral to follow; to
separate one's self from it is dangerous, but more dangerous for the
community than for the individual (because the Godhead punishes
the community for every outrage and every violation of its rights,
and the individual only in proportion). Now every tradition grows
continually more venerable, the farther off lies its origin, the more
this is lost sight of; the veneration paid it accumulates from
generation to generation, the tradition at last becomes holy and
excites awe; and thus in any case the morality of piety is a much
older morality than that which requires un-egoistic actions.

97.
Pleasure in Traditional Custom.—An important species of pleasure, and
therewith the source of morality, arises out of habit. Man does what
is habitual to him more easily, better, and therefore more willingly;
he feels a pleasure therein, and knows from experience that the
habitual has been tested, and is therefore useful; a custom that we
can live with is proved to be wholesome and advantageous in
contrast to all new and not yet tested experiments. According to
this, morality is the union of the pleasant and the useful; moreover,
it requires no reflection. As soon as man can use compulsion, he
uses it to introduce and enforce his customs; for in his eyes they are
proved as the wisdom of life. In the same way a company of
individuals compels each single one to adopt the same customs.
Here the inference is wrong; because we feel at ease with a
morality, or at least because we are able to carry on existence with
it, therefore this morality is necessary, for it seems to be the only
possibility of feeling at ease; the ease of life seems to grow out of it
alone. This comprehension of the habitual as a necessity of
existence is pursued even to the smallest details of custom,—as
insight into genuine causality is very small with lower peoples and
civilisations, they take precautions with superstitious fear that
everything should go in its same groove; even where custom is
difficult, hard, and burdensome, it is preserved on account of its
apparent highest usefulness. It is not known that the same degree
of well-being can also exist with other customs, and that even higher
degrees may be attained. We become aware, however, that all
customs, even the hardest, grow pleasanter and milder with time,
and that the severest way of life may become a habit and therefore
a pleasure.

98.
Pleasure and Social Instinct.—Out of his relations with other men, man
obtains a new species of pleasure in addition to those pleasurable
sensations which he derives from himself; whereby he greatly
increases the scope of enjoyment. Perhaps he has already taken too
many of the pleasures of this sphere from animals, which visibly feel
pleasure when they play with each other, especially the mother with
her young. Then consider the sexual relations, which make almost
every female interesting to a male with regard to pleasure, and vice
versa. The feeling of pleasure on the basis of human relations
generally makes man better; joy in common, pleasure enjoyed
together is increased, it gives the individual security, makes him
good-tempered, and dispels mistrust and envy, for we feel ourselves
at ease and see others at ease. Similar manifestations of pleasure
awaken the idea of the same sensations, the feeling of being like
something; a like effect is produced by common sufferings, the same
bad weather, dangers, enemies. Upon this foundation is based the
oldest alliance, the object of which is the mutual obviating and
averting of a threatening danger for the benefit of each individual.
And thus the social instinct grows out of pleasure.

99.
The Innocent Side of So-called Evil Actions.—All "evil" actions are
prompted by the instinct of preservation, or, more exactly, by the
desire for pleasure and the avoidance of pain on the part of the
individual; thus prompted, but not evil. "To cause pain per se" does
not exist, except in the brains of philosophers, neither does "to give
pleasure per se" (pity in Schopenhauer's meaning). In the social
condition before the State we kill the creature, be it ape or man,
who tries to take from us the fruit of a tree when we are hungry and
approach the tree, as we should still do with animals in inhospitable
countries. The evil actions which now most rouse our indignation,
are based upon the error that he who causes them has a free will,
that he had the option, therefore, of not doing us this injury. This
belief in option arouses hatred, desire for revenge, spite, and the
deterioration of the whole imagination, while we are much less
angry with an animal because we consider it irresponsible. To do
injury, not from the instinct of preservation, but as requital, is the
consequence of a false judgment and therefore equally innocent.
The individual can in the condition which lies before the State, act
sternly and cruelly towards other creatures for the purpose of
terrifying, to establish his existence firmly by such terrifying proofs
of his power. Thus act the violent, the mighty, the original founders
of States, who subdue the weaker to themselves. They have the
right to do so, such as the State still takes for itself; or rather, there
is no right that can hinder this. The ground for all-morality can only
be made ready when a stronger individual or a collective individual,
for instance society or the State, subdues the single
individuals,.draws them out of their singleness, and forms them into
an association.. Compulsion precedes morality, indeed morality itself
is compulsion for a time, to which one submits for the avoidance of
pain. Later on it becomes custom,—later still, free obedience, and
finally almost instinct,—then, like everything long accustomed and
natural, it is connected with pleasure—and is henceforth called
virtue.

100.
Shame.—Shame exists everywhere where there is a "mystery"; this,
however, is a religious idea, which was widely extended in the older
times of human civilisation. Everywhere were found bounded
domains to which access was forbidden by divine right, except under
certain conditions ; at first locally, as, for example, certain spots that
ought not to be trodden by the feet of the uninitiated, in the
neighbourhood of which these latter experienced horror and fear.
This feeling was a good deal carried over into other relations, for
instance, the sex relations, which, as a privilege and ἃδoυτον of
riper years, had to be withheld from the knowledge of the young for
their advantage, relations for the protection and sanctification of
which many gods were invented and were set up as guardians in the
nuptial chamber. (In Turkish this room is on this account called
harem, "sanctuary," and is distinguished with the same name,
therefore, that is used for the entrance courts of the mosques.) Thus
the kingdom is as a centre from which radiate power and glory, to
the subjects a mystery full of secrecy and shame, of which many
after-effects may still be felt among nations which otherwise do not
by any means belong to the bashful type. Similarly, the whole world
of inner conditions, the so-called "soul," is still a mystery for all who
are not philosophers, after it has been looked upon for endless ages
as of divine origin and as worthy of divine intercourse; according to
this it is an ἃδoυτον and arouses shame.

101.
Judge Not.—In considering earlier periods, care must be taken not to
fall into unjust abuse. The injustice in slavery, the cruelty in the
suppression of persons and nations, is not to be measured by our
standard. For the instinct of justice was not then so far developed.
Who dares to reproach the Genevese Calvin with the burning of the
physician Servet? It was an action following and resulting from his
convictions, and in the same way the Inquisition had a good right;
only the ruling views were false, and produced a result which seems
hard to us because those views have now grown strange to us.
Besides, what is the burning of a single individual compared with
eternal pains of hell for almost all! And yet this idea was universal at
that time, without essentially injuring by its dreadfulness the
conception of a God. With us, too, political sectarians are hardly and
cruelly treated, but because one is accustomed to believe in the
necessity of the State, the cruelty is not so deeply felt here as it is
where we repudiate the views. Cruelty to animals in children and
Italians is due to ignorance, i.e. the animal, through the interests of
Church teaching, has been placed too far behind man. Much that is
dreadful and inhuman in history, much that one hardly likes to
believe, is mitigated by the reflection that the one who commands
and the one who carries out are different persons,—the former does
not behold the right and therefore does not experience the strong
impression on the imagination; the latter obeys a superior and
therefore feels no responsibility. Most princes and military heads,
through lack of imagination, easily appear hard and cruel without
really being so. Egoism is not evil, because the idea of the
"neighbour"—the word is of Christian origin and does not represent
the truth—is very weak in us; and we feel ourselves almost as free
and irresponsible towards him as towards plants and stones. We
have yet to learn that others suffer, and this can never be completely
learnt.

102.
"Man Always Acts Rightly."—We do not complain of nature as immoral
because it sends a thunderstorm and makes us wet,—why do we call
those who injure us immoral? Because in the latter case we take for
granted a free will functioning voluntarily; in the former we see
necessity. But this distinction is an error. Thus we do not call even
intentional injury immoral in all circumstances; for instance, we kill a
fly unhesitatingly and intentionally, only because its buzzing annoys
us; we punish a criminal intentionally and hurt him in order to
protect ourselves and society. In the first case it is the individual
who, in order to preserve himself, or even to protect himself from
worry, does intentional injury; in the second case it is the State. All
morals allow intentional injury in the case of necessity, that is, when
it is a matter of self-preservation! But these two points of view
suffice to explain all evil actions committed by men against men, we
are desirous of obtaining pleasure or avoiding pain; in any case it is
always a question of self-preservation. Socrates and Plato are right:
whatever man does he always does well, that is, he does that which
seems to him good (useful) according to the degree of his intellect,
the particular standard of his reasonableness.

103.
The Harmlessness of Malice.—The aim of malice is not the suffering of
others in itself, but our own enjoyment; for instance, as the feeling
of revenge, or stronger nervous excitement. All teasing, even, shows
the pleasure it gives to exercise our power on others and bring it to
an enjoyable feeling of preponderance. Is it immoral to taste
pleasure at the expense of another's pain? Is malicious joy[3]
devilish, as Schopenhauer says? We give ourselves pleasure in
nature by breaking off twigs, loosening stones, fighting with wild
animals, and do this in order to become thereby conscious of our
strength. Is the knowledge, therefore, that another suffers through
us, the same thing concerning which we otherwise feel irresponsible,
supposed to make us immoral? But if we did not know this we would
not thereby have the enjoyment of our own superiority, which can
only manifest itself by the suffering of others, for instance in teasing.
All pleasure per se is neither good nor evil; whence should come the
decision that in order to have pleasure ourselves we may not cause
displeasure to others? From the point of view of usefulness alone,
that is, out of consideration for the consequences, for possible
displeasure, when the injured one or the replacing State gives the
expectation of resentment and revenge: this only can have been the
original reason for denying ourselves such actions. Pity aims just as
little at the pleasure of others as malice at the pain of others per se.
For it contains at least two (perhaps many more) elements of a
personal pleasure, and is so far self-gratification; in the first place as
the pleasure of emotion, which is the kind of pity that exists in
tragedy, and then, when it impels to action, as the pleasure of
satisfaction in the exercise of power. If, besides this, a suffering
person is very dear to us, we lift a sorrow from ourselves by the
exercise of sympathetic actions. Except by a few philosophers, pity
has always been placed very low in the scale of moral feelings, and
rightly so.

104.
Self-defence.—If self-defence is allowed to pass as moral, then almost
all manifestations of the so-called immoral egoism must also stand;
men injure, rob, or kill in order to preserve or defend themselves, to
prevent personal injury; they lie where cunning and dissimulation
are the right means of self-preservation. Intentional injury, when our
existence or safety (preservation of our comfort) is concerned, is
conceded to be moral; the State itself injures, according to this point
of view, when it punishes. In unintentional injury, of course, there
can be nothing immoral, that is ruled by chance. Is there, then, a
kind of intentional injury where our existence or the preservation of
our comfort is not concerned? Is there an injuring out of pure
malice, for instance in cruelty? If one does not know how much an
action hurts, it is no deed of malice; thus the child is not malicious
towards the animal, not evil; he examines and destroys it like a toy.
But do we ever know entirely how an action hurts another? As far as
our nervous system extends we protect ourselves from pain; if it
extended farther, to our fellow-men, namely, we should do no one
an injury (except in such cases as we injure ourselves, where we cut
ourselves for the sake of cure, tire and exert ourselves for the sake
of health). We conclude by analogy that something hurts somebody,
and through memory and the strength of imagination we may suffer
from it ourselves. But still what a difference there is between
toothache and the pain (pity) that the sight of toothache calls forth!
Therefore, in injury out of so-called malice the degree of pain
produced is always unknown to us; but inasmuch as there is
pleasure in the action (the feeling of one's own power, one's own
strong excitement), the action is committed, in order to preserve the
comfort of the individual, and is regarded, therefore, from a similar
point of view as defence and falsehood in necessity. No life without
pleasure; the struggle for pleasure is the struggle for life. Whether
the individual so fights this fight that men call him good, or so that
they call him evil, is determined by the measure and the constitution
of his intellect.

105.
Recompensing Justice.—Whoever has completely comprehended the
doctrine of absolute irresponsibility can no longer include the so-
called punishing and recompensing justice in the idea of justice,
should this consist of giving to each man his due. For he who is
punished does not deserve the punishment, he is only used as a
means of henceforth warning away from certain actions; equally so,
he who is rewarded does not merit this reward, he could not act
otherwise than he did. Therefore the reward is meant only as an
encouragement to him and others, to provide a motive for
subsequent actions; words of praise are flung to the runners on the
course, not to the one who has reached the goal. Neither
punishment nor reward is anything that comes to one as one's own;
they are given from motives of usefulness, without one having a
right to claim them. Hence we must say, "The wise man gives no
reward because the deed has been well done," just as we have said,
"The wise man does not punish because evil has been committed,
but in order that evil shall not be committed." If punishment and
reward no longer existed, then the strongest motives which deter
men from certain actions and impel them to certain other actions,
would also no longer exist; the needs of mankind require their
continuance; and inasmuch as punishment and reward, blame and
praise, work most sensibly on vanity, the same need requires the
continuance of vanity.

106.
At the Waterfall.—In looking at a water-fall we imagine that there is
freedom of will and fancy in the countless turnings, twistings, and
breakings of the waves; but everything is compulsory, every
movement can be mathematically calculated. So it is also with
human actions; one would have to be able to calculate every single
action beforehand if one were all-knowing; equally so all progress of
knowledge, every error, all malice. The one who acts certainly
labours under the illusion of voluntariness; if the world's wheel were
to stand still for a moment and an all-knowing, calculating reason
were there to make use of this pause, it could foretell the future of
every creature to the remotest times, and mark out every track upon
which that wheel would continue to roll. The delusion of the acting
agent about himself, the supposition of a free will, belongs to this
mechanism which still remains to be calculated.

107.
Irresponsibility and Innocence.—The complete irresponsibility of man
for his actions and his nature is the bitterest drop which he who
understands must swallow if he was accustomed to see the patent
of nobility of his humanity in responsibility and duty. All his
valuations, distinctions, disinclinations, are thereby deprived of value
and become false,—his deepest feeling for the sufferer and the hero
was based on an error; he may no longer either praise or blame, for
it is absurd to praise and blame nature and necessity. In the same
way as he loves a fine work of art, but does not praise it, because it
can do nothing for itself; in the same way as he regards plants, so
must he regard his own actions and those of mankind. He can
admire strength, beauty, abundance, in themselves; but must find
no merit therein,—the chemical progress and the strife of the
elements, the torments of the sick person who thirsts after recovery,
are all equally as little merits as those struggles of the soul and
states of distress in which we are torn hither and thither by different
impulses until we finally decide for the strongest—as we say (but in
reality it is the strongest motive which decides for us). All these
motives, however, whatever fine names we may give them, have all
grown out of the same root, in which we believe the evil poisons to
be situated; between good and evil actions there is no difference of
species, but at most of degree. Good actions are sublimated evil
ones; evil actions are vulgarised and stupefied good ones. The single
longing of the individual for self-gratification (together with the fear
of losing it) satisfies itself in all circumstances: man may act as he
can, that is as he must, be it in deeds of vanity, revenge, pleasure,
usefulness, malice, cunning; be it in deeds of sacrifice, of pity, of
knowledge. The degrees of the power of judgment determine
whither any one lets himself be drawn through this longing; to every
society, to every individual, a scale of possessions is continually
present, according to which he determines his actions and judges
those of others. But this standard changes constantly; many actions
are called evil and are only stupid, because the degree of
intelligence which decided for them was very low. In a certain sense,
even, all actions are still stupid; for the highest degree of human
intelligence which can now be attained will assuredly be yet
surpassed, and then, in a retrospect, all our actions and judgments
will appear as limited and hasty as the actions and judgments of
primitive wild peoples now appear limited and hasty to us. To
recognise all this may be deeply painful, but consolation comes
after; such pains are the pangs of birth. The butterfly wants to break
through its chrysalis: it rends and tears it, and is then blinded and
confused by the unaccustomed light, the kingdom of liberty. In such
people as are capable of such sadness—and how few are!—the first
experiment made is to see whether mankind can change itself from
a moral into a wise mankind. The sun of a new gospel throws its
rays upon the highest point in the soul of each single individual, then
the mists gather thicker than ever, and the brightest light and the
dreariest shadow lie side by side. Everything is necessity—so says
the new knowledge, and this knowledge itself is necessity.
Everything is innocence, and knowledge is the road to insight into
this innocence. Are pleasure, egoism, vanity necessary for the
production of the moral phenomena and their highest result, the
sense for truth and justice in knowledge; were error and the
confusion of the imagination the only means through which mankind
could raise itself gradually to this degree of self-enlightenment and
self-liberation—who would dare to undervalue these means? Who
would dare to be sad if he perceived the goal to which those roads
led? Everything in the domain of morality has evolved, is
changeable, unstable, everything is dissolved, it is true; but
everything is also streaming towards one goal. Even if the inherited
habit of erroneous valuation, love and hatred, continue to reign in
us, yet under the influence of growing knowledge it will become
weaker; a new habit, that of comprehension, of not loving, not
hating, of overlooking, is gradually implanting itself in us upon the
same ground, and in thousands of years will perhaps be powerful
enough to give humanity the strength to produce wise, innocent
(consciously innocent) men, as it now produces unwise, guilt-
conscious men,—that is the necessary preliminary step, not its
opposite.

You might also like